import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.*;



public class Client {

	private final double ORIGINALPRICE = 26.77;
	private final double INVESTMENT = 30000;
	private double currentPrice;
	private HttpClient httpclient;
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws JSONException 
	 * @throws ParseException 
	 */
	private void refresh() throws ClientProtocolException, IOException, ParseException, JSONException {
		
		HttpGet httpget = new HttpGet("http://bitcoincharts.com/t/markets.json");
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		
		if (entity != null) {
		    InputStream instream = entity.getContent();
		    try {
		    	 String source = EntityUtils.toString(entity); 
		         JSONArray allMarkets = new JSONArray(source);
	
		         for (int i = 0; i < allMarkets.length(); i++) {
		        	 if (allMarkets.getJSONObject(i).get("symbol").equals("mtgoxUSD")) {
		        		 this.currentPrice = (double) allMarkets.getJSONObject(i).get("close");
		        	 }
		        	 	
		         }
		    } finally {
		        instream.close();
		    }
		}
	}
	
	public Client(){
		super();
		httpclient = new DefaultHttpClient();
		currentPrice = 0;
	}
	
	public double getProfit(){
		return (currentPrice/ORIGINALPRICE - 1.03)*INVESTMENT;
	}
	
	public double getCurrentPrice() {
		try {
			refresh();
		} catch (Exception e) {
		
		}
		return currentPrice;
	}
	
	

}
